package com.senseuni.da.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Base64
import com.elvishew.xlog.XLog
import com.senseuni.da.db.entity.MediaEntity
import java.io.*

object MediaUtil {

    public const val PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCOJf1fsFhvuVEpzNkoa2C2VOz9p16HJ4jXuhHsg6jSZTP/R5J1ZTL3WTTVn5U4nsNVH2aojmi2UiAkHj5Gij9sKYS6/pYBb0C8xxXbGHZdXvHQPiJVxANUAivI5+/wDcnFYL7ZddHilbRC4EI0uKh044Pv4O3JRtsOB3eeTS9XgQIDAQAB"
//    private const val PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCmyAczQk2BOmi2lWE7L6EGx2BB7CYqwzHs8VydJxKNXQf2RhHbqUABcotw2sT4Z9PUoudrrLQsNZQvHyeVnqlAo7pNPmKKSz4Dgo0L4Wd12z5t9kXn5maZ16CMzvNYdYdxT5azDoAzMVNZdoYnkJGPVuSIv3lmopOGOBiACQ/A6wIDAQAB"
    private const val ALLOWED_CHARACTERS = "abcdefghijklmnopqrstuvwxyz1234567890"

    fun generateRandomString(length: Int, allowedChars: String = ALLOWED_CHARACTERS): String {
        return (1..length)
            .map { allowedChars.random() }
            .joinToString("")
    }

    fun decrypt(source: String, key:String): String {
        //先对key解密
        XLog.d("解密前的Key:$key")
        val aesKey = RsaUtils.decryptByPublicKey(PUBLIC_KEY, key)
        XLog.d("解密后的Key:$aesKey")
        return AESUtils.decrypt(source, aesKey)
    }

    fun encrypt(source: String): Array<String> {
        var aesKey = SpUtil.getMediaKey()
        if (aesKey.isEmpty()) {
            aesKey = generateRandomString(16)
            SpUtil.saveMediaKey(aesKey)
        }
        val key = RsaUtils.encryptByPublicKey(PUBLIC_KEY, aesKey)
        val encryptSource = AESUtils.encrypt(source, aesKey)
        return arrayOf(encryptSource, key)
    }

    fun convertImageToBase64(path: String?): String? {
        if (path.isNullOrEmpty()) {
            return null
        }

        return try {
            val imageFile = File(path)
            if (!imageFile.exists()) {
                return null
            }
            val fileInputStream = FileInputStream(imageFile)
            val byteArrayOutputStream = ByteArrayOutputStream()
            val buffer = ByteArray(4096)
            var length: Int
            while (fileInputStream.read(buffer).also { length = it } != -1) {
                byteArrayOutputStream.write(buffer, 0, length)
            }
            fileInputStream.close()
            byteArrayOutputStream.close()
            val imageBytes = byteArrayOutputStream.toByteArray()
            Base64.encodeToString(imageBytes, Base64.DEFAULT)
        } catch (e: IOException) {
            e.printStackTrace()
            null
        }
    }

    fun convertBase64ToImage(base64: String, imageDir:String, mediaEntity: MediaEntity?) : String {
        val bitmap: Bitmap?
        try {
            val decode: ByteArray = Base64.decode(base64, Base64.DEFAULT)
            bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.size)
        } catch (e: Exception) {
            XLog.e("image base64 decode fail:"+ e.message)
            return "image base64 decode fail:" + e.message
        }
        if (bitmap == null) {
            XLog.e("image base64 decode fail")
            return "image base64 decode fail"
        }
        val file = File(imageDir, "${System.currentTimeMillis()}.jpg")
        try {
            val fos = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
            fos.flush()
            fos.close()
        } catch (e: FileNotFoundException) {
            XLog.e("base64 save fail")
            return "base64 save fail:" + e.message
        }
        mediaEntity?.apply {
            mimeType = "image"
            fileName = file.name
            fileSize = file.length()
            path = file.absolutePath
            width = bitmap.width
            height = bitmap.height
        }
        bitmap.recycle()
        return ""
    }

}